package com.example.safeassistan.home.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.safeassistan.R;
import com.example.safeassistan.base.BaseModel;
import com.example.safeassistan.base.BaseVPFragment;
import com.example.safeassistan.common.UserData;
import com.example.safeassistan.constants.UrlConstants;
import com.example.safeassistan.home.activity.DeviceInfoDetail;
import com.example.safeassistan.home.activity.DeviceRepairEdit;
import com.example.safeassistan.home.activity.DevicerepairProgress;
import com.example.safeassistan.home.activity.RiskPointDetail;
import com.example.safeassistan.home.activity.RiskPointList;
import com.example.safeassistan.home.adapter.DeviceFragmentAdapter;
import com.example.safeassistan.home.adapter.HomeCheckRecordFragmentAdapter;
import com.example.safeassistan.home.adapter.RiskPointAdapter;
import com.example.safeassistan.home.model.DeviceListModel;
import com.example.safeassistan.home.model.HomeCheckRecordModel;
import com.example.safeassistan.http.HttpRequest;
import com.example.safeassistan.http.HttpStringCallBack;
import com.example.safeassistan.risk.model.RiskPointListSearchModel;
import com.example.safeassistan.utile.EventBusBean;
import com.example.safeassistan.utile.JsonUtils;
import com.example.safeassistan.widget.SlideRecyclerView;
import com.example.safeassistan.widget.WarningDialog;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.example.safeassistan.constants.Constants.PAGESIZE;

public class DeviceFragment extends BaseVPFragment {
    private Context context;
    private View view;
    private DeviceFragmentAdapter adapter;
    private List<DeviceListModel.ResultDTO.RecordsDTO> data;
    private SlideRecyclerView rcView;
    private SmartRefreshLayout refresh;
    private LinearLayout llNodata;
    private int type=1;//类型   1主要设备 2特种设备
    private Integer currentPage=1;
    private int count=0;
    private String name="";

    public static DeviceFragment newInstance(int  type) {
        Bundle arguments = new Bundle();
        arguments.putInt("type",type);
        DeviceFragment fl = new DeviceFragment();
        fl.setArguments(arguments);
        return fl;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.device_fragment, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }

    public void initView(){
        Bundle bundle = getArguments();
         type = bundle.getInt("type");
        rcView=view.findViewById(R.id.rcView);
        llNodata=view.findViewById(R.id.llNodata);
        refresh=view.findViewById(R.id.refresh);
        setView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void upLoadSuccess(EventBusBean eventBus){
        if (eventBus.getCode()==101){
            name=eventBus.getMsg();
            getData();
        }
    }

    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            if (!name.equals("")){
                map.put("name",name);
            }
            map.put("type", type);
            map.put("pageNo", String.valueOf(currentPage));
            map.put("pageSize",String.valueOf(PAGESIZE));

        } catch (JSONException e) {
            e.printStackTrace();
        }

        new HttpRequest(context).doPost(UrlConstants.taskdeviceManage, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), DeviceListModel.class);
                        if (obj instanceof DeviceListModel) {
                            DeviceListModel model=(DeviceListModel) obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    data=model.getResult().getRecords();
                                    adapter=new DeviceFragmentAdapter(data,context);
                                    rcView.setLayoutManager(new LinearLayoutManager(context));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }

                                            adapter.setOnItemClickListener(new DeviceFragmentAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.Adapter adapter, View v, int position) {
                DeviceInfoDetail.actionStart(getContext(),data.get(position).getId(),data.get(position).getName());
            }
        });
        adapter.setOnDeleteClickListener(new DeviceFragmentAdapter.OnDeleteClickLister() {
            @Override
            public void onDeleteClick(View view, int position) {
                switch (view.getId()){
                    case R.id.tvUnBind:
                        //解绑
                        WarningDialog warningDialog=new WarningDialog(context,"确定要解绑该设备吗？","取消","确定","");
                        warningDialog.setClicklistener(new WarningDialog.ClickListenerInterface() {
                            @Override
                            public void doCancel() {
                                warningDialog.dismiss();
                            }

                            @Override
                            public void doConfirm() {
                                warningDialog.dismiss();
                                deviceUntie(data.get(position).getId());
                            }
                        });
                        warningDialog.show();
                        break;
//                    case R.id.tvRepair:
//                        //报修
////                        switch (data.get(position).getId()){
////                            case "0":
//                                DeviceRepairEdit.actionStart(context,data.get(position).getId(),data.get(position).getName());
////                                break;
////                            case "1":
////                                DevicerepairProgress.actionStart(context,1);
////                                break;
////                            case "2":
////                                DevicerepairProgress.actionStart(context,2);
////                                break;
////                        }
//                        break;
                }
            }
        });
                                } else {
                                    llNodata.setVisibility(View.VISIBLE);
                                    rcView.setVisibility(View.GONE);
                                    refresh.finishRefreshWithNoMoreData();
                                    adapter.notifyDataSetChanged();
                                }
                            } else {
                                 data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishLoadMore();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishLoadMoreWithNoMoreData();//将不会再次触发加载更多事件
                                }
                            }
                        }
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }

    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {
        if (isVisible){
            EventBus.getDefault().register(this);
        }else {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    protected void onFragmentFirstVisible() {
        getData();
    }

    //获取数据
    public void deviceUntie(String deviceId){
        Map map = new HashMap<>();
        map.put("deviceId", deviceId);
        new HttpRequest(context).doGet(UrlConstants.taskdeviceUntie, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        Object obj = JsonUtils.fromJson(result.toString(), BaseModel.class);
                       Toast.makeText(context,"解绑设备成功！！！",Toast.LENGTH_SHORT).show();
                       getData();
                    }else {
                        Toast.makeText(context,message,Toast.LENGTH_SHORT).show();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }
}
